package com.ejuornal.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.ejuornal.bean.User;
import com.ejuornal.dao.UserDao;

/**
 * 项目名称：ejuornal 
 * 类名称：UserDaoImpl 
 * 类描述： 用户管理持久层实现（主要功能对于用户表的CRUD） 
 * 创建人：陈晨 
 * 创建时间：Jan 23, 2013 5:29:51 PM 
 * 修改人：陈晨 
 * 修改时间：Jan 23, 2013 5:29:51 PM 
 * 修改备注：
 * @version
 */

@Component("userDao")
public class UserDaoImpl extends DaoSupport<User> implements UserDao {
	public void add(String sql, Object... objs) {
		super.add(sql, objs);
	}

	public void batchDelete(String sql, int... ids) {
		super.batchDelete(sql, ids);
	}

	@Override
	public void update(String sql, Object... objs) {
		super.update(sql, objs);
	}

	public boolean isExists(String userName) {
		String sql = "SELECT count(*) FROM t_user WHERE userName = ?";
		int result = super.getJdbcTemplate().queryForInt(sql,
				new Object[] { userName });

		if (result != 0) {
			return true; // 用户名存在返回true
		} else {
			return false; // 用户名不存在返回false
		}
	}

	public User findByEmail(String email) {
		System.out.println("dao + "+email);
		String sql = "select * from t_user where email=?";
        List<User> users = super.getJdbcTemplate().query(sql,
                new Object[] { email }, new RowMapper<User>() {

                    public User mapRow(ResultSet rs, int rowNum)
                            throws SQLException {
                        User user = new User();
                        user.setUserId(rs.getInt("userId"));
//                      gcf 修改以前是user.setEmail(user.getEmail());
                        user.setEmail(rs.getString("email"));
                        user.setUserName(rs.getString("userName"));
                        user.setPassword(rs.getString("password"));
                        user.setRoleId(rs.getInt("roleId"));
                        user.setRegisteDate(rs.getDate("registeDate"));

                        return user;
                    }
                });
        if(users.isEmpty()) {
            return null;
        }
        return users.get(0);
		        
	}

	public User findById(int userId) {
		String sql = "SELECT * FROM t_user WHERE userId = ?";
		List<User> users = super.getJdbcTemplate().query(sql,
				new Object[] { userId }, new RowMapper<User>() {

					public User mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						User user = new User();
						user.setUserId(rs.getInt("userId"));
//						gcf 修改以前是user.setEmail(user.getEmail());
						user.setEmail(rs.getString("email"));
						user.setUserName(rs.getString("userName"));
						user.setPassword(rs.getString("password"));
						user.setRoleId(rs.getInt("roleId"));
						user.setRegisteDate(rs.getDate("registeDate"));

						return user;
					}
				});
		if(users.isEmpty()) {
            return null;
        }
        return users.get(0);
	}

    public User findByUserName(String userName) {
        String sql = "select * from t_user where userName=?";
        List<User> users = super.getJdbcTemplate().query(sql,
                new Object[] { userName }, new RowMapper<User>() {

                    public User mapRow(ResultSet rs, int rowNum)
                            throws SQLException {
                        User user = new User();
                        user.setUserId(rs.getInt("userId"));
//                      gcf 修改以前是user.setEmail(user.getEmail());
                        user.setEmail(rs.getString("email"));
                        user.setUserName(rs.getString("userName"));
                        user.setPassword(rs.getString("password"));
                        user.setRoleId(rs.getInt("roleId"));
                        user.setRegisteDate(rs.getDate("registeDate"));

                        return user;
                    }
                });

        if(users.isEmpty()) {
            return null;
        }
        return users.get(0);
    }


    public boolean update(User user) {
        String sql = "update t_user set roleId = ? where userName = ?";
        int row = super.getJdbcTemplate().update(sql, new Object[]{ user.getRoleId(),user.getUserName()});
        if(row > 0) {
            return true;
        }
        return false;
    }
	@Override
	public boolean isExistsByEmail(String email) {
		String sql = "SELECT count(*) FROM t_user WHERE email = ?";
		int result = super.getJdbcTemplate().queryForInt(sql,
				new Object[] { email });

		if (result != 0) {
			return true; // 该邮箱已使用过返回true
		} else {
			return false; // 该邮箱未使用返回false
		}
	}
	
	public List<User> getListUsers(int ChiefUserId,String sql){
		return getJdbcTemplate().query(sql, new UserMapper(), new Object[]{ChiefUserId});
	}

	@Override
	public User getUser(int articalId,String sql) {
		// TODO Auto-generated method stub
		List<User> users = getJdbcTemplate().query(sql, new Object[]{articalId}, new UserMapper());
		if(users.isEmpty()) {
            return null;
        }
        return users.get(0);
	}

	@Override
	public boolean updateByUserId(User user) {
		String sql = "update t_user set roleId = ? where userId = ?";
        int row = super.getJdbcTemplate().update(sql, new Object[]{ user.getRoleId(),user.getUserId()});
        if(row > 0) {
            return true;
        }else{
        	return false;
        }
	}

}

final class UserMapper implements RowMapper<User> {

	@Override
	public User mapRow(ResultSet rs, int num) throws SQLException {
		// TODO Auto-generated method stub
		User  user = new User();
		user.setEmail(rs.getString("email"));
		user.setPassword(rs.getString("password"));
		user.setRegisteDate(rs.getDate("registeDate"));
		user.setRoleId(rs.getInt("roleId"));
		user.setUserId(rs.getInt("userId"));
		user.setUserName(rs.getString("userName"));
		return user;
	}
	
	
}

